package com.itheima.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.itheima.interceptors.LoginInterceptor;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public User findByUserId(Integer id) {
        User u = userMapper.findByUserId(id);
        return u;
    }

    @Override
    public void register(String username, String password) {
        //加密
        String md5String = Md5Util.getMD5String(password);
        //添加
        userMapper.add(username, md5String);
    }

    @Override
    public User login(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public User updateByUserId(User user) {
        User existU = userMapper.findByUserId(user.getId());

        if (existU != null) {
            user.setCreateTime(existU.getCreateTime());
            user.setUpdateTime(LocalDateTime.now());
            BeanUtil.copyProperties(user, existU, CopyOptions.create().setIgnoreNullValue(true));
        }

        userMapper.updateUser(existU);

        return existU;
    }

    @Override
    public String updateCurUserAvatar(String url) {
        User user = LoginInterceptor.curUser.get();
        userMapper.updateAvatarById(user.getId(), url);
        return url;
    }

    @Override
    public void updateCurUserPassword(String password) {
        User user = LoginInterceptor.curUser.get();
        password = Md5Util.getMD5String(password);
        userMapper.updateCurUserPassword(user.getId(), password);
    }
}
